// pages/abulkPage/abulkPage.js
const app = getApp()
const WXAPI = require('../../api/api')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 0,
      // 是否显示左上角图标   1表示显示    0表示不显示
      title: ' ',
      // 导航栏 中间的标题
      textColor: '#FFFFFF',
      // 标题颜色
      bgColor: '#F75D0B',
      // 导航栏背景颜色
      isloading: false
    },
    navList: [],
    typeList: [{
        id: 1,
        value: '爆品推荐'
      },
      {
        id: 2,
        value: '今日上新'
      },
      {
        id: 3,
        value: '离我最近'
      },
      {
        id: 4,
        value: '价格优先'
      },
    ],
    shopImgList: [],
    current: 1,
    imgHttp: app.globalData.imgHttp,
    module: 1, //推荐模块 1 爆品推荐 2 今日上新 3 离我最近 4价格优先
    lnt: '', //经度
    lat: '', //纬度
    bulkList: [],
    isPull: true, //是否刷新
    lodingtype: 1, //加载状态（0：加载中  1：加载完成没有更多）
    pageSize: 10,
    pageNum: 1,
    loginShow: true, //是否登录弹出窗
    grouponId: '',
    isScrollY: false,
    jtkCode: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      statusHeight: app.gettop.height,
      status: app.gettop.status,
      navHeight: app.gettop.navHeight,
      mobbleBottom: app.mobile.mobbleBottom
    });
    this.isGetSetting();
    this.getBanner();
    this.getNavigationList()
    var jtkCode = wx.getStorageSync('jtkCode')
    console.log('jtkCode', jtkCode)
    if (!jtkCode) {
      this.getUnionId()
    } else {
      this.setData({
        jtkCode: jtkCode
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.login_dialog = this.selectComponent("#login_dialog");
    this.login_dialog.loginHide()
    // var token = wx.getStorageSync('token')
    // if(token){
    //   this.login_dialog.loginHide()
    // }
    this.getNavigationList()
    if (!app.globalData.lat && !app.globalData.lnt) {
      this.isGetSetting();
    }

  },
  // 静默授权-获取聚推客code
  async getUnionId() {
    var appId = app.globalData.appid
    var code = await this.getCode()
    console.log('哈哈哈', code)
    var data = {
      appId: appId,
      code: code,
    }
    WXAPI.getUnionId(data, res => {
      if (res.code == 200) {
        wx.setStorageSync('jtkCode', res.result)
        this.setData({
          jtkCode: res.result
        })
      }
    })
  },
  getCode() {
    // 登录 
    let that = this;
    return new Promise((resolve, reject) => {
      wx.login({
        success: function (res) {
          if (res.code) {
            resolve(res.code)
            console.log('获取code', res.code)
          } else {
            reject()
            console.log('获取code失败', res.errMsg)
          }
        }
      })
    })

  },
  //获取首页轮播图
  getBanner() {
    WXAPI.indexBanner('', res => {
      if (res.code == 200) {
        this.setData({
          shopImgList: res.result
        })
      }
    })
  },
  //
  getNavigationList() {
    WXAPI.navigationList('', res => {
      if (res.code == 200) {
        this.setData({
          navList: res.result
        })
      }
    })
  },

  //获取团购列表
  getBulkList() {
    const that = this;
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    var data = {
      module: this.data.module,
      lnt: this.data.lnt,
      lat: this.data.lat,
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum,
    }
    WXAPI.bulkList(data, res => {

      const {
        size,
        total,
        records
      } = res.result;
      var list = [];
      var bulkList = this.data.bulkList;
      if (res.code === 200) {
        if (this.data.pageNum >= Math.ceil(total / size)) {
          this.setData({
            lodingtype: 1,
            isPull: false
          });
        } else {
          this.setData({
            lodingtype: 0,
            isPull: true
          });
        }

        wx.hideLoading();
        list = records, this.setData({
          bulkList: bulkList.concat(list)
        });
      }
    });
  },

  //获取位置授权
  isGetSetting() {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    console.log("经纬度");
    var that = this; // 判断用户是否授权

    wx.getSetting({
      success: res => {
        var statu = res.authSetting;
        console.log('statu', statu['scope.userLocation'])
        if (!statu['scope.userLocation']) {
          //没授权
          //1、获取当前位置坐标
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              console.log("经纬度", res);
              app.globalData.lat = res.latitude; //维度
              app.globalData.lnt = res.longitude; //经度
              that.setData({
                lat: res.latitude,
                //维度
                lnt: res.longitude,
                //经度
                unauthorized: true
              });
              wx.hideLoading();
              that.getBulkList();
            },
            fail: function (res) {
              that.getBulkList();
              that.setData({
                unauthorized: false
              });
            }
          });
        } else {
          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              console.log("经纬度1", res);
              app.globalData.lat = res.latitude; //维度
              app.globalData.lnt = res.longitude; //经度

              that.setData({
                lat: res.latitude,
                //维度
                lnt: res.longitude,
                //经度
                unauthorized: true
              });
              wx.hideLoading();
              that.getBulkList();
            },
            fail: function (res) {
              that.getBulkList();
              that.setData({
                unauthorized: false
              });
            }
          });
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //跳转动态类型
  handleTypeListNew(e) {
    const item = e.currentTarget.dataset.item
    if (item.redirectUrl == '') {
      return
    }
    // （redirectType: 1 小程序 2 H5 3 聚推客）
    if (item.redirectType == 1) {
      if (item.appid) {
        wx.navigateToMiniProgram({
          appId: item.appid, //appid
          path: item.redirectUrl, //path
          envVersion: 'release', //开发版develop 开发版 trial   体验版 release 正式版 
          success(res) {
            console.log('成功')
            // 打开成功
          }
        })
      }
    } else if (item.redirectType == 2) {
      var obj = {
        phone: wx.getStorageSync('phone'),
        time: new Date().getTime()
      }
      console.log(obj)
      wx.navigateTo({
        url: '/userPageC/pages/externalH5/externalH5?url=' + item.redirectUrl+'&data='+obj
      });
    } else if (item.redirectType == 3) {

      WXAPI.getJtkH5DetailUrl({
        id: item.id,
        jtkCode: this.data.jtkCode
      }, res => {
        console.log(res)
        var url = res.result
        console.log('url', url)
        var arr = url.split('?')
        console.log('arr', arr)
        var data = arr[1].split("&")
        var obj = {}
        data.forEach(item => {
          console.log('item', item)
          var str = item.split('=')
          obj[str[0]] = str[1]
          console.log('obj', obj)
        })
        obj = JSON.stringify(obj)
        wx.navigateTo({
          url: '/userPageC/pages/externalH5/externalH5?url=' + arr[0] + '&data=' + obj + '&type=true'
        });
      })
    } else {
      wx.navigateTo({
        url: item.redirectUrl,
      })
    }
  },
  /* 授权成功后执行 */
  loginSuccess() {

  },
  //
  handleswiper(e) {
    var url = e.currentTarget.dataset.url
    wx.navigateTo({
      url: url,

    });
  },
  //切换选项
  handleType(e) {
    const id = e.currentTarget.dataset.id;

    this.setData({
      current: id,
      module: id,
      bulkList: [],
      pageNum: 1,
    })
    this.getBulkList();
  },
  //查看团购
  handleDetail(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/userPageC/pages/abulkDetail/abulkDetail?id=' + id,

    });
  },
  //立即购买
  handlepay(e) {
    var id = e.currentTarget.dataset.id
    const token = wx.getStorageSync('token');
    if (token) {
      wx.navigateTo({
        url: '/userPageC/pages/confirmOrder/confirmOrder?grouponId=' + id,
      });
    } else {
      this.login_dialog.loginShow()
    }
  },
  //关闭弹窗
  handleChoose() {
    this.setData({
      loginShow: false,
    })
  },
  onPageScroll(e) {
    var that = this;
    var scrollY = e.scrollTop
    // console.log('scrollY',scrollY)
    if (scrollY > 50) {
      that.setData({
        isScrollY: true,
      })

    } else if (scrollY < 50) {
      that.setData({
        isScrollY: false,
      })

    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.isPull == true) {
      var pageNum = this.data.pageNum;
      pageNum++;
      console.log("触底了", pageNum);
      this.setData({
        pageNum: pageNum
      });
      this.getBulkList();
    }
  },
})